<?php

namespace App\Exports;

use App\Models\Sign;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class SignsExport extends DefaultValueBinder implements FromArray, WithColumnWidths, WithCustomValueBinder
{
    use Exportable;

    public function __construct(public array $listQuery)
    {
    }
    public function array(): array
    {
        // $investment_meeting_id = $this->listQuery['investment_meeting_id'] ?? '';
        // $category_id = $this->listQuery['category_id'] ?? '';
        // $investment_people_id = $this->listQuery['investment_people_id'] ?? '';
        // $name = $this->listQuery['name'] ?? '';
        $lists = Sign::with(['category', 'investmentMeeting', 'investmentPerson'])
            ->when($this->listQuery['category_id'], function ($query, $category_id) {
                $query->where('category_id', $category_id);
            })
            ->when($this->listQuery['investment_people_id'], function ($query, $investment_people_id) {
                $query->where('investment_people_id', $investment_people_id);
            })
            ->when($this->listQuery['investment_meeting_id'], function ($query, $investment_meeting_id) {
                $query->where('investment_meeting_id', $investment_meeting_id);
            })
            ->when($this->listQuery['name'], function ($query, $name) {
                $query->where('name', 'like', '%' . $name . '%');
            })
            ->orderByDesc('id')->get();
        $arr = [[
            '招商会名称',
            '厂家名称',
            '类目',
            '招商员',
            '签到时间',
        ]];
        foreach ($lists as $v) {
            $arr[] = [
                $v->investmentMeeting->title,
                $v->name,
                $v->category->name,
                $v->investmentPerson ? $v->investmentPerson->name . '【' . $v->investmentPerson->nickname . '】' : '',
                $v->created_at,
            ];
        }
        return $arr;
    }

    public function columnWidths(): array
    {
        return [
            'A' => 20, 'B' => 20, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 20, 'I' => 20, 'J' => 20, 'K' => 20,
        ];
    }

    public function bindValue(Cell $cell, $value)
    {
        $column = $cell->getColumn();
        if (in_array($column, ['E', 'F', 'G'])) {
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }
}
